package org.linlinjava.litemall.wx.service;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.partnerpayments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.core.util.IpUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.core.RedisCache;
import org.linlinjava.litemall.db.dao.SysConfigMapper;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.SysConfig;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.service.SysConfigService;
import org.linlinjava.litemall.db.util.BalanceConstant;
import org.linlinjava.litemall.wx.dto.PayInfo;
import org.linlinjava.litemall.wx.dto.PayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.linlinjava.litemall.wx.util.WxResponseCode.*;

@Service
public class PayService {

    private final Log logger = LogFactory.getLog(PayService.class);

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private com.github.binarywang.wxpay.service.WxPayService wxPayService;

    /**
     * 付款订单的预支付会话标识
     */
    @Transactional
    public Object prepay(Integer userId, PayRequest body, HttpServletRequest request) {
        PayProcessor processor = (PayProcessor) BeanUtil.getBean( body.getAttach() + "-pay");
        if (processor==null) {
            return ResponseUtil.badArgument();
        }
        Boolean autoPay = false; // 订单系统支付标识
        BigDecimal balance = null; // 用户余额
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer orderId = body.getOrderId();
        Integer way = body.getWay(); // 支付方式
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }
        PayInfo payInfo = processor.checkPayInfo(userId, body.getOrderId());
        if (payInfo==null) {
            return ResponseUtil.fail(ORDER_INVALID_OPERATION, "订单不能支付");
        }
        if (payInfo.getPrice().compareTo(BigDecimal.ZERO) == 0) { // 如果订单金额为0元.不唤醒微信支付，自动支付成功
            autoPay = true;
        }
        if (way != null && way == 1 && !autoPay) { //尝试使用系统余额支付 way = 1 为余额支付
            BigDecimal last = userService.addBalance(userId, payInfo.getPrice().negate(), BalanceConstant.CONSUME);
            if (last != null) {
                autoPay = true;
                balance = last; // 更新余额
            }
        }
        if (autoPay) { // 系统支付
            processor.recordSuccess(payInfo.getOrderSn());
            HashMap<String, Object> data = new HashMap<>();
            data.put("done", autoPay);
            if (balance != null) {
                data.put("balance", balance);
            }
            return ResponseUtil.ok(data);
        } else { // 微信支付
            LitemallUser user = userService.findById(userId);
            String openid = user.getWeixinOpenid();
            if (openid == null) {
                return ResponseUtil.fail(AUTH_OPENID_UNACCESS, "订单不能支付");
            }
            WxPayMpOrderResult result = null;
            try {
                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                orderRequest.setOutTradeNo(payInfo.getOrderSn());
                orderRequest.setSubOpenid(openid);
                orderRequest.setBody("订单：" + payInfo.getOrderSn());
                orderRequest.setAttach(body.getAttach());
                // 元转成分
                int fee = 0;
                BigDecimal actualPrice = payInfo.getPrice();
                fee = actualPrice.multiply(new BigDecimal(100)).intValue();
                orderRequest.setTotalFee(fee);
                orderRequest.setSpbillCreateIp(IpUtil.getIpAddr(request));
                result = wxPayService.createOrder(orderRequest);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseUtil.fail(ORDER_PAY_FAIL, "订单不能支付");
            }
            return ResponseUtil.ok(result);
        }
    }

    /**
     * 微信付款成功或失败回调接口
     * <p>
     * 1. 检测当前订单是否是付款状态;
     * 2. 设置订单付款成功状态相关信息;
     * 3. 响应微信商户平台.
     *
     * @param request  请求内容
     * @param response 响应内容
     * @return 操作结果
     */
    @Transactional
    public Object payNotify(HttpServletRequest request, HttpServletResponse response) {
        String xmlResult = null;
        try {
            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail(e.getMessage());
        }

        WxPayOrderNotifyResult result = null;
        try {
            result = wxPayService.parseOrderNotifyResult(xmlResult);

            if (!WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode())) {
                logger.error(xmlResult);
                throw new WxPayException("微信通知支付失败！");
            }
            if (!WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())) {
                logger.error(xmlResult);
                throw new WxPayException("微信通知支付失败！");
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail(e.getMessage());
        }

        logger.info("处理腾讯支付平台的订单支付");
        logger.info(result);

        String orderSn = result.getOutTradeNo();
        String payId = result.getTransactionId();

        // 分转化成元
        String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
        String attach = result.getAttach();
        PayProcessor processor = (PayProcessor) BeanUtil.getBean( attach + "-pay");
        return processor.recordSuccess(orderSn, totalFee, payId);
    }

    private JsapiService jsapiService;

    @Autowired
    private RedisCache redisCache;




    public PrepayResponse buildPrepayRequest(String productName,String orderNum,String openid) {
        Map<String, String> sysConfig = redisCache.getCacheMap("sys_config");
        PrepayRequest request = new PrepayRequest();
        Payer payer = new Payer();
        payer.setOpenid(openid);
        Amount amount = new Amount();
        amount.setTotal(100);
        request.setAmount(amount);
        request.setAppid(sysConfig.get("wx_sub-app-id"));
        request.setMchid(sysConfig.get("wx_mch-id"));
        request.setDescription(productName);
        request.setNotifyUrl(sysConfig.get("wx_notify-url"));
        request.setOutTradeNo(orderNum);
        // 调用下单方法，得到应答
        PrepayResponse response = jsapiService.prepay(request);
        return response;
    }

}
